package emergency.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.util.ArrayList;
import java.util.List;

import emergency.adapter.EmergencyRecordAdapter;
import emergency.dto.Alert;
import emergency.dto.AlertRecordDto;
import emergency.network.DealEmergency;
import emergency.network.GetEmergencyRecord;
import inter.Delegate;
import inter.SimpleInfo;
import model.OwnUser;
import utils.TimeUtil;

/**
 * Created by Administrator on 2016/4/8.
 */
public class EmergencyRecord extends UIHandler.BaseActivity {

    public static List<AlertRecordDto> alertsStatic = null;

    ListView lv_emergency;
    List<AlertRecordDto> alerts = new ArrayList<AlertRecordDto>();
    String realname = MyApplication.getOwnUser().getUser_RealName();
    Button btn_type;
    EmergencyRecordAdapter emergencyRecordAdapter = new EmergencyRecordAdapter();

    {
        emergencyRecordAdapter.setAlerts(alerts);
    }

    // 过滤水厂信息
    List<AlertRecordDto> passOutInfo( List<AlertRecordDto> alertRecordDtos)
    {
        List<AlertRecordDto> alertRecordDtos1 = new ArrayList<AlertRecordDto>();
        String area = MyApplication.aCache.getAsString(SimpleInfo.PLANTNAME);
        if (area.equals("枝江"))
        {
            alertRecordDtos1 = alertRecordDtos;
        }
        else
        {
            for (AlertRecordDto dto:alertRecordDtos)
            {
                if (dto.getAlertWaterPlant().contains(area))
                {
                    alertRecordDtos1.add(dto);
                }
            }
        }

        return alertRecordDtos1;
    }

    Delegate emergencyRecordResult = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (!response.startsWith("[")) return;
            String area = MyApplication.aCache.getAsString(SimpleInfo.PLANTNAME);
            if (area == null)
            {
                EmergencyRecord.this.finish();
            }

            List<AlertRecordDto> alertRecordDtos = JSON.parseArray(response, AlertRecordDto.class);
            List<AlertRecordDto> alertRecordDtos1 = new ArrayList<AlertRecordDto>();
            if (area.equals("枝江"))
            {
                alertRecordDtos1 = alertRecordDtos;
            }
            else
            {
                for (AlertRecordDto dto:alertRecordDtos)
                {
                    if (dto.getAlertWaterPlant().contains(area))
                    {
                        alertRecordDtos1.add(dto);
                    }
                }
            }

            if (alertRecordDtos1.isEmpty())
            {
                EmergencyRecord.this.finish();
            }

            alerts.clear();
            alerts.addAll(alertRecordDtos1);
            emergencyRecordAdapter.notifyDataSetChanged();
        }

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MyApplication.share(),"获取数据失败",Toast.LENGTH_SHORT).show();
            EmergencyRecord.this.finish();
        }
    };

    GetEmergencyRecord getEmergencyRecord = new GetEmergencyRecord();

    {
        getEmergencyRecord.setDelegate(emergencyRecordResult);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emergencyrecord);
        initview();
        initdata();
    }

    private void initdata() {

        if (alertsStatic != null)
        {
            List<AlertRecordDto> dtos = passOutInfo(alertsStatic);
            emergencyRecordAdapter.setAlerts(dtos);
            emergencyRecordAdapter.notifyDataSetChanged();
        }
        else {
            getEmergencyRecord.get();
        }
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == btn_type)
            {
                Intent intent = new Intent(EmergencyRecord.this,EmergencyType.class);
                EmergencyRecord.this.startActivity(intent);
            }
        }
    };

    private void initview() {
        lv_emergency = (ListView) findViewById(R.id.id_lv_emergency);
        lv_emergency.setAdapter(emergencyRecordAdapter);

        lv_emergency.setDividerHeight((int)getResources().getDimension(R.dimen.y8));
//        lv_emergency.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                showdeal(view, position);
//                return false;
//            }
//        });

        btn_type = (Button) findViewById(R.id.id_btn_type);
        btn_type.setOnClickListener(onClickListener);
    }

    int positiondeal;
    private void showdeal(View view, int position) {
        View popupView = LayoutInflater.from(this).inflate(R.layout.popup, null);
        final PopupWindow popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = popupView.getMeasuredWidth();
        int popupHeight = popupView.getMeasuredHeight();
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, (location[0] + view.getWidth() / 2) - popupWidth / 2,
                location[1] + view.getHeight() - popupHeight);

        positiondeal = position;
        final int p = position;
        // 点击处理预警
        popupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertRecordDto alert = alerts.get(p);
                DealEmergency dealEmergency = new DealEmergency();
                dealEmergency.setAlertAlertId(alert.getId().getAlertId()+"");
                dealEmergency.setDisposealertname(realname);
                dealEmergency.setRecordTime(alert.getId().getTime());
                dealEmergency.setDelegate(dealEmergencyResult);
                dealEmergency.get();
                popupWindow.dismiss();
            }
        });
    }

    // 处理预警结果
    Delegate dealEmergencyResult = new Delegate() {
        @Override
        public void onResponse(String response) {
            if (response.equals("\"success\""))
            {
                Toast.makeText(EmergencyRecord.this,"处理成功", Toast.LENGTH_SHORT).show();
                alerts.get(positiondeal).setFlag("1");
                alerts.get(positiondeal).setDisposealertname(realname);
                emergencyRecordAdapter.notifyDataSetChanged();
            }
            else if (response.equals("\"hasDisposed\""))
            {
                Toast.makeText(EmergencyRecord.this,"该记录已经处理了",Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(EmergencyRecord.this,"修改失败",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        alertsStatic = null;
    }
}
